<template>
  <div class="mt-export-dialog">
    <el-dialog
      :title="process_type==='1'?'产品导出':'产品编辑'"
      :width="'80%'"
      :visible.sync="childFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="export-component"
      @close="hide"
    >
      <el-tabs type="border-card">
        <el-tab-pane v-if="ids.length===1" label="产品信息(不填默认使用模板)">
          <el-form
            v-if="website && website.id"
            :model="submitParams.firstStep_single"
            label-position="top"
            label-width="80px"
            style="margin-left: 2%"
          >
            <el-form-item>
              <el-button type="danger" style="float:right;" icon="el-icon-delete" size="mini" @click="handleRemoveProductInfo">清空
              </el-button>
              <el-button type="success" style="float:right;" icon="el-icon-delete" size="mini" @click="handleCopyProductInfo">复制产品信息
              </el-button>
            </el-form-item>
            <el-form-item label="name">
              <el-input v-model="submitParams.firstStep_single.name" />
            </el-form-item>
            <el-form-item label="短描述">
              <el-input v-model="submitParams.firstStep_single.short_desc" type="textarea" />
              <!--<tinymce ref="mt_export_single_description" :height="300" v-model="submitParams.firstStep_single.short_desc"></tinymce>-->
            </el-form-item>
            <el-form-item label="description">
              <tinymce ref="mt_export_single_description" v-model="submitParams.firstStep_single.description" :height="300" />
            </el-form-item>

            <el-form-item label="Meta title">
              <el-input v-model="submitParams.firstStep_single.meta_title" />
            </el-form-item>

            <el-form-item label="Meta description">
              <el-input v-model="submitParams.firstStep_single.meta_description" />
            </el-form-item>

            <el-form-item label="Meta keywords">
              <el-input v-model="submitParams.firstStep_single.meta_keywords" />
            </el-form-item>

          </el-form>
        </el-tab-pane>
        <el-tab-pane v-if="website" v-loading="templateLoading" label="选择模版">
          <el-form
            v-if="website && website.id"
            :model="submitParams.firstStep"
            label-position="left"
            label-width="40px"
            style="margin-left: 2%"
          >
            <el-form-item>
              <el-button type="success" style="float:right;" icon="el-icon-delete" size="mini" @click="handleRemoveTemplateChoose">清空选择
              </el-button>
            </el-form-item>

            <el-form-item label="标题模版：" label-width="10%">

              <el-transfer
                v-model="submitParams.firstStep.selectedTt"
                filterable
                :filter-method="filterMethod"
                :titles="['可选标题模版', '已选标题模版']"
                filter-placeholder="输入搜索"
                :data="dataSource.firstStep.titleTemplates"
                :props="{ key: 'id', label: 'name' }"
              >
                <span slot-scope="{ option }" :title="option.name">{{ option.name }}</span>
              </el-transfer>
            </el-form-item>

            <el-form-item label="关键词模版：" label-width="10%">
              <el-transfer
                v-model="submitParams.firstStep.selectedKt"
                filterable
                :filter-method="filterMethod"
                :titles="['可选关键词模版', '已选关键词模版']"
                filter-placeholder="输入搜索"
                :data="dataSource.firstStep.keywordTemplates"
                :props="{ key: 'id', label: 'name' }"
              >
                <span slot-scope="{ option }" :title="option.name">{{ option.name }}</span>
              </el-transfer>
            </el-form-item>

            <el-form-item label="meta描述模版：" label-width="10%">
              <el-transfer
                v-model="submitParams.firstStep.selectedMdt"
                filterable
                :filter-method="filterMethod"
                :titles="['可选meta描述模版', '已选meta描述模版']"
                filter-placeholder="输入搜索"
                :data="dataSource.firstStep.metaDescTemplates"
                :props="{ key: 'id', label: 'name' }"
              >
                <span slot-scope="{ option }" :title="option.name">{{ option.name }}</span>
              </el-transfer>
            </el-form-item>

            <el-form-item label="短描述模版：" label-width="10%">

              <el-transfer
                v-model="submitParams.firstStep.selectedDt"
                filterable
                :filter-method="filterMethod"
                :titles="['可选短描述模版', '已选短描述模版']"
                filter-placeholder="输入搜索"
                :data="dataSource.firstStep.descTemplates"
                :props="{ key: 'id', label: 'name' }"
              >
                <span slot-scope="{ option }" :title="option.name">{{ option.name }}</span>
              </el-transfer>
            </el-form-item>

            <el-form-item label="长描述模版：" label-width="10%">

              <el-transfer
                v-model="submitParams.firstStep.selectedLdt"
                filterable
                :filter-method="filterMethod"
                :titles="['可选长描述模版', '已选长描述模版']"
                filter-placeholder="输入搜索"
                :data="dataSource.firstStep.longDescTemplates"
                :props="{ key: 'id', label: 'name' }"
              >
                <span slot-scope="{ option }" :title="option.name">{{ option.name }}</span>
              </el-transfer>
            </el-form-item>

          </el-form>
          <div>
            <el-button
              v-if="website && website.id"
              size="mini"
              type="success"
              plain
              style="margin-left:20px;margin-right: 20px"
              icon="el-icon-eye"
              @click="handleTemplatePreview"
            >模版预览
            </el-button>
            <el-button plain size="mini" icon="el-icon-refresh" title="刷新" @click="fetchTemplates" />

          </div>
        </el-tab-pane>

        <el-tab-pane v-if="process_type === '1'" v-loading="associationLoading" label="配置属性">
          <el-row v-if="website" :gutter="20" style="margin-right: 20px">
            <el-col :span="7">
              <el-tree
                ref="propTree"
                :data="dataSource.secondStep.associations"
                default-expand-all
                show-checkbox
                node-key="name"
                :default-checked-keys="dataSource.secondStep.default_associations"
                :props="{ children: 'children', label: 'name' }"
              />
              <el-row :gutter="5" style="margin-top: 20px">
                <el-col :offset="2" :span="4">
                  <el-button
                    v-if="dataSource.secondStep.associations.length"
                    plain
                    size="mini"
                    type="success"
                    icon="el-icon-plus"
                    @click="handleSecondStepAdd"
                  />
                </el-col>
                <el-col :offset="4" :span="4">
                  <el-button
                    v-if="dataSource.secondStep.associations.length"
                    plain
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    @click="handleSecondStepRemove"
                  />
                </el-col>
                <el-button plain size="mini" icon="el-icon-refresh" title="刷新" @click="fetchAssociations" />
              </el-row>
            </el-col>
            <el-col :span="17">
              <el-table
                size="mini"
                :data="submitParams.secondStep.tableData"
                border
                style="width: 100%;"
              >
                <el-table-column
                  align="center"
                  label="属性"
                  min-width="224"
                >
                  <template slot-scope="scope">
                    <span>{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="增加的价格($)"
                  width="224"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.impact_price"
                      size="mini"
                      type="number"
                      class="mt-input-price"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="增加的重量(kg)"
                  width="246"
                >
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.impact_weight"
                      size="mini"
                      type="number"
                      class="mt-input-price"
                    />
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <div v-else>还未配置该站点</div>
        </el-tab-pane>
        <el-tab-pane v-if="ids.length===1" label="选择产品图片">
          <!--<el-button @click="handleViewCrawlProductImage()">选择图片</el-button>-->
          <crawlimage
            ref="mt_crawlimage"
            :is-dialog="isImageDialog"
            :product_id="single_row_id"
            titlename="选择产品图片"
            :image-dialog-visible="crawlimage_visualbe"
            :source="source"
            @closeDialog="crawlimage_visualbe=false"
            @handleSelectionChange="handleSelectionImageChange"
          />
        </el-tab-pane>
        <el-tab-pane v-if="process_type === '1'" v-loading="exportLoading" label="导出">
          <div v-if="website">
            <el-form
              :model="submitParams.thirdStep"
              label-position="left"
              label-width="220px"
              style="padding-left: 5%; width:100%;padding-right: 5%"
            >

              <el-tooltip content="如果产品价格为0，使用此价格" placement="bottom">
                <el-form-item label="默认价格">
                  <el-input
                    v-model="submitParams.thirdStep.default_price"
                    size="small"
                    type="number"
                    class="mt-supplier-code-input"
                  />
                </el-form-item>
              </el-tooltip>

              <el-form-item label="库存">
                <el-input
                  v-model="submitParams.thirdStep.quantity"
                  size="small"
                  type="number"
                  class="mt-supplier-code-input"
                />
              </el-form-item>

              <el-tooltip content="是否可用" placement="bottom">
                <el-form-item label="Status">
                  <el-checkbox
                    v-model="submitParams.thirdStep.status"
                    size="small"
                    true-label="Y"
                    false-label="N"
                  />
                </el-form-item>
              </el-tooltip>

              <el-tooltip content="是否可直接被下单" placement="bottom">
                <el-form-item label="Aviable For order">
                  <el-checkbox
                    v-model="submitParams.thirdStep.avail_for_order"
                    size="small"
                    true-label="Y"
                    false-label="N"
                  />
                </el-form-item>
              </el-tooltip>

              <el-tooltip content="标签以 , 分割。如果产品没有标签，则使用该值" placement="bottom">
                <el-form-item label="tags">
                  <el-input
                    v-model="submitParams.thirdStep.tags"
                    size="small"
                    class="mt-supplier-code-input"
                  />
                </el-form-item>
              </el-tooltip>

              <el-tooltip content="交易货币形式" placement="bottom">
                <el-form-item label="Currency">
                  <el-select
                    v-model="submitParams.thirdStep.currency"
                    placeholder="请选择货币"
                    class="mt-supplier-code-input"
                  >
                    <el-option
                      v-for="item in [{id:1,value:'USD'}]"
                      :key="item.id"
                      :label="item.value"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-tooltip>

              <el-tooltip content="上传到哪个目录。如果产品没有 目录id，则使用该值" placement="bottom">
                <el-form-item label="Name of Associated Category">
                  <el-input v-model="filterText" placeholder="输入关键字进行过滤" size="mini" clearable />
                  <el-tree
                    ref="exportProductTree"
                    :data="dataSource.thirdStep.catalogs"
                    show-checkbox
                    node-key="id"
                    :default-expanded-keys="dataSource.thirdStep.catalogs.length?[dataSource.thirdStep.catalogs[0].id]:[]"
                    :default-checked-keys="defaultCheckedKeys"
                    :filter-node-method="filterCategoryNode"
                    :expand-on-click-node="false"
                    :props="{ children: 'children', label: 'name' }"
                    check-strictly
                    @check-change="()=>{this.submitParams.thirdStep.target_catalogs=this.$refs.exportProductTree.getCheckedNodes()}"
                  >
                    <span slot-scope="{ node, data }" class="custom-tree-node">
                      <span>{{ data.id + ' | ' + node.label }}</span>
                      <span><el-button
                        v-if="data.children.length"
                        type="text"
                        size="mini"
                        style="margin-right: 20px"
                        @click="showAddCategoryDialog(data)"
                      >添加</el-button></span>
                    </span>
                  </el-tree>
                  <el-button
                    plain
                    icon="el-icon-refresh"
                    title="刷新"
                    size="mini"
                    @click="handleFetchWebsiteCatalogs"
                  />
                </el-form-item>

              </el-tooltip>

              <el-tooltip content="默认目录" placement="bottom">
                <el-form-item label="Default Category">
                  <el-select
                    v-model="submitParams.thirdStep.default_catalogs"
                    filterable
                    class="mt-supplier-code-input"
                    placeholder="请选择默认目录"
                  >
                    <el-option
                      v-for="item in submitParams.thirdStep.target_catalogs"
                      :key="item.id"
                      :label="item.id + ' |  ' + item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-tooltip>

              <el-tooltip content="统一该批次图片尺寸" placement="bottom">
                <el-form-item label="图片尺寸 width,height">
                  <el-input
                    v-model="submitParams.thirdStep.image_size"
                    placeholder="width,height"
                    size="mini"
                    clearable
                  />
                </el-form-item>
              </el-tooltip>

            </el-form>
            <div>
              <el-button
                size="mini"
                type="warning"
                style="margin-left: calc(48% - 100px)"
                @click="handleExport('excel')"
              >检测Excel
              </el-button>

              <el-button
                size="mini"
                type="danger"
                style="margin-left: 20px"
                @click="handleExport('')"
              >同步至站点
              </el-button>
            </div>
          </div>
          <div v-else>还未配置该站点</div>
        </el-tab-pane>
        <el-tab-pane v-if="process_type === '2'" label="远程编辑">
          <div v-if="website">
            <el-form
              :model="submitParams.thirdStepRemoate"
              label-position="left"
              label-width="220px"
              style="padding-left: 5%; width:100%;padding-right: 5%"
            >

              <el-tooltip content="留空表示不编辑" placement="bottom">
                <el-form-item label="默认价格">
                  <el-input
                    v-model="submitParams.thirdStepRemoate.default_price"
                    size="small"
                    type="number"
                    class="mt-supplier-code-input"
                  />
                </el-form-item>
              </el-tooltip>

              <el-tooltip content="目录树" placement="bottom">
                <el-form-item label="目录树(参考)">
                  <el-input v-model="filterText" placeholder="输入关键字进行过滤" size="mini" clearable />
                  <el-tree
                    :data="dataSource.thirdStepRemoate.catalogs"
                    show-checkbox
                    node-key="id"
                    :show-checkbox="false"
                    :filter-node-method="filterCategoryNode"
                    :expand-on-click-node="false"
                    :props="{ children: 'children', label: 'name' }"
                    check-strictly
                    @check-change="()=>{this.submitParams.thirdStepRemoate.target_catalogs=this.$refs.exportProductTree.getCheckedNodes()}"
                  >
                    <span slot-scope="{ node, data }" class="custom-tree-node">
                      <span>{{ data.id + ' | ' + node.label }}</span>
                      <span><el-button
                        v-if="data.children.length"
                        type="text"
                        size="mini"
                        style="margin-right: 20px"
                        @click="showAddCategoryDialog(data)"
                      >添加</el-button></span>
                    </span>
                  </el-tree>
                  <el-button
                    plain
                    icon="el-icon-refresh"
                    title="刷新"
                    size="mini"
                    @click="handleFetchWebsiteCatalogs"
                  />
                </el-form-item>

              </el-tooltip>

              <el-tooltip content="默认目录ID" placement="bottom">
                <el-form-item label="Default Category ID(填写数字id)">
                  <el-input
                    v-model="submitParams.thirdStepRemoate.default_catalogs"
                    size="small"
                    type="number"
                    class="mt-supplier-code-input"
                  />
                </el-form-item>
              </el-tooltip>
              <!--<el-tooltip content="是否可用" placement="bottom">-->
              <!--<el-form-item label="Status">-->
              <!--<el-checkbox size="small" true-label='Y' false-label='N'-->
              <!--v-model="submitParams.thirdStepRemoate.status">-->
              <!--</el-checkbox>-->
              <!--</el-form-item>-->
              <!--</el-tooltip>-->

            </el-form>
            <div style="text-align: center">
              <el-button
                size="mini"
                type="danger"
                @click="handleRemoteEdit('')"
              >点击修改
              </el-button>
            </div>
          </div>
          <div v-else>还未配置该站点</div>
        </el-tab-pane>
      </el-tabs>

      <el-dialog title="模版预览" :visible.sync="templatePreviewDialogVisible" width="100%" append-to-body>
        <el-tabs type="border-card">
          <el-tab-pane label="产品ID">{{ dataSource.firstStep.templatePreviewData.id }}</el-tab-pane>
          <el-tab-pane label="产品名称">{{ dataSource.firstStep.templatePreviewData.name }}</el-tab-pane>
          <el-tab-pane label="标题">{{ dataSource.firstStep.templatePreviewData.title }}</el-tab-pane>
          <el-tab-pane label="关键词"><span v-html="dataSource.firstStep.templatePreviewData.keyword" />
          </el-tab-pane>
          <el-tab-pane label="短描述" name="desc"><span v-html="dataSource.firstStep.templatePreviewData.desc" />
          </el-tab-pane>
          <el-tab-pane label="meta描述" name="meta"><span v-html="dataSource.firstStep.templatePreviewData.meta" />
          </el-tab-pane>
          <el-tab-pane label="长描述" name="meta"><span v-html="dataSource.firstStep.templatePreviewData.l_desc" />
          </el-tab-pane>
        </el-tabs>
      </el-dialog>

      <el-dialog
        v-loading.fullscreen.lock="addCategoryLoading"
        title="添加目录"
        :visible.sync="addCategoryDialogVisible"
        width="80%"
        append-to-body
        class="mt-add-category-dialog"
      >
        <el-form :model="submitParams.addCategory" label-position="left" label-width="140px">
          <el-form-item label="* Name">
            <el-input v-model="submitParams.addCategory.name" />
          </el-form-item>

          <el-form-item label="Displayed">
            <el-switch
              v-model="submitParams.addCategory.active"
              active-color="#13ce66"
              active-value="1"
              inactive-value="0"
              inactive-color="#ff4949"
            />
          </el-form-item>

          <br>
          <el-form-item label="Description">
            <tinymce ref="mt_export_component" v-model="submitParams.addCategory.description" :height="300" />
          </el-form-item>

          <el-form-item label="Meta title">
            <el-input v-model="submitParams.addCategory.meta_title" />
          </el-form-item>

          <el-form-item label="Meta description">
            <el-input v-model="submitParams.addCategory.meta_description" />
          </el-form-item>

          <el-form-item label="Meta keywords">
            <el-input v-model="submitParams.addCategory.meta_keywords" />
          </el-form-item>

          <el-form-item label="* Friendly URL">
            <el-input v-model="submitParams.addCategory.friendly_url" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addCategoryDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAddCategory">确 定</el-button>
        </span>
      </el-dialog>

    </el-dialog>

  </div>
</template>

<script>
import { Get as GetTt } from '@/api/erp/elicink/titleTemplate'
import { Get as GetDt } from '@/api/erp/elicink/descriptionTemplate'
import { Get as GetMdt } from '@/api/erp/elicink/metaDescriptionTemplate'
import { Get as GetKt } from '@/api/erp/elicink/keywordTemplate'
import { Get as GetLdt } from '@/api/erp/elicink/longDescriptionTemplate'
import { product_export } from '@/api/erp/elicink/product'
import { templatePreview } from '@/api/erp/elicink/templatePreview'
import {
  CatalogTree as GetWebsiteCatalogs,
  AssociationTree as GetAssociations,
  AddCategory
} from '@/api/erp/elicink/website'
import crawlimage from '@/views/crawl/elements/crawlimage'

const axios = require('axios')
const _ = require('lodash')
import Tinymce from '@/components/Tinymce'

const _coos_mapper = {
  'None': 0, // None
  'S  (Round 600g ) +$45.99': 45.99, // 'S  (Round 600g ) +$45.99'
  'L (Round 1000g)+$68.99': 68.99, // 'L (Round 1000g)+$68.99'
  'L (Bell Shape 1000g)+$68.99': 68.99, // 'L (Bell Shape 1000g)+$68.99'
  'XL (Round 1400g)+$88.99': 88.99, // 'XL (Round 1400g)+$88.99'

  'Peach Skin': 0, // 'Peach Skin'
  'Super Soft Velvet': 14, // 'Super Soft Velvet'
  'Smooth Knit': 16, // 'Smooth Knit'
  '2Way Tricot': 26, // '2Way Tricot'
  'PP Cotton': 0, // 'PP Cotton'
  'Eiderdown Cotton': 0, // 'Eiderdown Cotton'

  '150x50cm': 12,
  '160x50cm': 22,
  '100x35cm': 0
}

const _default_associations = [
  'S  (Round 600g ) +$45.99',
  'L (Round 1000g)+$68.99',
  'L (Bell Shape 1000g)+$68.99',
  'XL (Round 1400g)+$88.99',
  'None',

  '150x50cm',
  '160x50cm',
  '100x35cm',

  'Peach Skin',
  'Super Soft Velvet',
  'Smooth Knit',
  '2Way Tricot'
]

export default {
  name: 'ExportComponent',
  components: { Tinymce, crawlimage },
  props: ['website', 'source', 'ids', 'exportDialogVisible', 'process_type', 'single_row'],
  data() {
    return {
      crawlimage_visualbe: false,
      single_row_id: '',
      isImageDialog: false,
      filterText: '',
      existed_associated_category_ids: [],
      defaultCheckedKeys: [],
      addCategoryLoading: false,
      addCategoryDialogVisible: false, // 添加目录 dialog 可见

      associationLoading: false,
      templateLoading: false,
      exportLoading: false,
      childFormVisible: false,
      activeName: 'id',
      templatePreviewDialogVisible: false,
      dataSource: {
        firstStep: {
          titleTemplates: [],
          descTemplates: [],
          metaDescTemplates: [],
          keywordTemplates: [],
          longDescTemplates: [],
          templatePreviewData: {}
        },
        firstStep_single: { // 产品上传，可以手动编辑这些信息
          name: '',
          short_desc: '',
          meta_desc: '',
          meta_title: '',
          keywords: '',
          description: ''
        },
        secondStep: {
          associations: [],
          default_associations: _default_associations.concat()
        },
        thirdStep: {
          catalogs: []
        },
        thirdStepRemoate: {
          catalogs: []
        }
      },

      // 提交参数
      submitParams: {
        firstStep: {
          selectedTt: [],
          selectedKt: [],
          selectedMdt: [],
          selectedDt: [],
          selectedLdt: []
        },
        firstStep_single: { // 单个产品上传，可以手动编辑这些信息
          name: '',
          short_desc: '',
          meta_desc: '',
          meta_title: '',
          keywords: '',
          description: '',
          img_ids: [] // 选择的产品图片dis如果不选择默认选择所有
        },
        secondStep: {
          tableData: []
        },
        thirdStep: {
          default_price: 0,
          quantity: 3000,
          status: 'Y',
          avail_for_order: 'N', // 是否可直接被下单
          tags: '',
          currency: 'USD',
          target_catalogs: [],
          default_catalogs: '',
          image_size: ''
        },
        thirdStepRemoate: {
          default_price: '',
          quantity: 3000,
          status: 'Y',
          avail_for_order: 'N', // 是否可直接被下单
          tags: '',
          currency: 'USD',
          target_catalogs: [],
          default_catalogs: '',
          image_size: ''
        },
        addCategory: {
          name: '',
          active: '1',
          id_parent: null,
          description: '',
          meta_title: '',
          meta_description: '',
          meta_keywords: '',
          friendly_url: ''
        }
      }
    }
  },
  computed: {
    category_name() {
      return this.submitParams.addCategory.name
    }
  },
  watch: {
    filterText(val) {
      this.$refs.exportProductTree.filter(val)
    },
    category_name(val) {
      if (val) this.submitParams.addCategory.friendly_url = _.trim(val, '-').split(' ').join('-')
    },
    website(new_value, old_value) {
      if (!(_.isEqual(new_value, old_value) && _.isBoolean(new_value))) {
        // 进行重置
        this.reset()
        this.fetchCatlogsAndAssociations()
        this.fetchTemplates()
        if (this.website.domain.includes('coosfly.com')) {
          this.submitParams.thirdStep.image_size = '539,800'
        }
      }
    },
    single_row(new_value) {
      if (new_value !== '') {
        if (this.source === 'local') {
          this.single_row_id = new_value.id
          this.dataSource.firstStep_single.name = new_value.name
          this.submitParams.firstStep_single.name = new_value.name
        } else {
          this.dataSource.firstStep_single.name = new_value.name
          this.dataSource.firstStep_single.short_desc = new_value.short_desc
          this.dataSource.firstStep_single.meta_desc = new_value.meta_desc
          this.dataSource.firstStep_single.meta_title = new_value.meta_title
          this.dataSource.firstStep_single.keywords = new_value.meta_keywords
          this.dataSource.firstStep_single.description = new_value.description
          // 修改数据源
          this.submitParams.firstStep_single.name = new_value.name
          this.submitParams.firstStep_single.short_desc = new_value.short_desc
          this.submitParams.firstStep_single.meta_desc = new_value.meta_desc
          this.submitParams.firstStep_single.meta_title = new_value.meta_title
          this.submitParams.firstStep_single.keywords = new_value.meta_keywords
          this.submitParams.firstStep_single.description = new_value.description
          this.single_row_id = new_value.item_id
          this.$nextTick(() => {
            if (this.$refs.mt_export_single_description.hasInit && new_value.description != null) {
              this.$refs.mt_export_single_description.setContent(new_value.description != null ? new_value.description : '')
            }
          }
          )
        }
      }
    },
    exportDialogVisible(v) {
      this.childFormVisible = v
    },
    source(v) {
      this.source = v
    }
  },
  methods: {
    handleViewCrawlProductImage() {
      this.crawlimage_visualbe = true
    },
    handleSelectionImageChange(val) {
      this.submitParams.firstStep_single.img_urls = val.map(m => {
        return m.url
      })
    },
    reset() {
      this.activeName = 'id'
      this.templatePreviewDialogVisible = false
      this.dataSource = {
        firstStep: {
          titleTemplates: [],
          descTemplates: [],
          metaDescTemplates: [],
          keywordTemplates: [],
          longDescTemplates: [],
          templatePreviewData: {}
        },
        firstStep_single: { // 单个产品上传，可以手动编辑这些信息
          name: '',
          short_desc: '',
          meta_desc: '',
          meta_title: '',
          keywords: '',
          description: ''
        },
        secondStep: {
          associations: [],
          default_associations: _default_associations.concat()
        },
        thirdStep: {
          catalogs: []
        },
        thirdStepRemoate: {
          default_price: '',
          quantity: 3000,
          status: 'Y',
          avail_for_order: 'N', // 是否可直接被下单
          tags: '',
          currency: 'USD',
          target_catalogs: [],
          default_catalogs: '',
          image_size: ''
        }
      }
      this.submitParams = {
        firstStep: {
          selectedTt: [],
          selectedKt: [],
          selectedMdt: [],
          selectedDt: [],
          selectedLdt: []
        },
        firstStep_single: { // 单个产品上传，可以手动编辑这些信息
          name: '',
          short_desc: '',
          meta_desc: '',
          meta_title: '',
          keywords: '',
          description: '',
          img_urls: []
        },
        secondStep: {
          tableData: []
        },
        thirdStep: {
          default_price: 0,
          quantity: 3000,
          status: 'Y',
          avail_for_order: 'N', // 是否可直接被下单
          tags: '',
          currency: 'USD',
          target_catalogs: [],
          default_catalogs: ''
        },
        thirdStepRemoate: {
          default_price: '',
          quantity: 3000,
          status: 'Y',
          avail_for_order: 'N', // 是否可直接被下单
          tags: '',
          currency: 'USD',
          target_catalogs: [],
          default_catalogs: '',
          image_size: ''
        },
        addCategory: {
          name: '',
          active: '1',
          id_parent: null,
          description: '',
          meta_title: '',
          meta_description: '',
          meta_keywords: '',
          friendly_url: ''
        }
      }
    },
    handleRemoveTemplateChoose() {
      this.submitParams.firstStep.selectedTt = []
      this.submitParams.firstStep.selectedKt = []
      this.submitParams.firstStep.selectedMdt = []
      this.submitParams.firstStep.selectedDt = []
      this.submitParams.firstStep.selectedLdt = []
    },
    handleRemoveProductInfo() {
      this.submitParams.firstStep_single.name = ''
      this.submitParams.firstStep_single.short_desc = ''
      this.submitParams.firstStep_single.meta_desc = ''
      this.submitParams.firstStep_single.meta_title = ''
      this.submitParams.firstStep_single.keywords = ''
      this.submitParams.firstStep_single.description = ''
    },
    handleCopyProductInfo() {
      this.submitParams.firstStep_single.name = this.dataSource.firstStep_single.name
      this.submitParams.firstStep_single.short_desc = this.dataSource.firstStep_single.short_desc
      this.submitParams.firstStep_single.meta_desc = this.dataSource.firstStep_single.meta_desc
      this.submitParams.firstStep_single.meta_title = this.dataSource.firstStep_single.meta_title
      this.submitParams.firstStep_single.keywords = this.dataSource.firstStep_single.keywords
      this.submitParams.firstStep_single.description = this.dataSource.firstStep_single.description
      this.$nextTick(() => {
        if (this.$refs.mt_export_single_description.hasInit && this.submitParams.firstStep_single.description != null) {
          this.$refs.mt_export_single_description.setContent(this.submitParams.firstStep_single.description != null ? this.submitParams.firstStep_single.description : '')
        }
      }
      )
    },
    filterMethod(query, item) {
      return item.name.indexOf(query) > -1
    },
    fetchTemplates() {
      this.templateLoading = true
      const w = `website=${this.website.id}`
      axios.all([GetDt(null, w), GetTt(null, w), GetKt(null, w), GetMdt(null, w), GetLdt(null, w)])
        .then(axios.spread((dt, tt, kt, mdt, ldt) => {
          this.dataSource.firstStep.descTemplates = dt.data.data
          this.dataSource.firstStep.titleTemplates = tt.data.data
          this.dataSource.firstStep.keywordTemplates = kt.data.data
          this.dataSource.firstStep.metaDescTemplates = mdt.data.data
          this.dataSource.firstStep.longDescTemplates = ldt.data.data

          this.submitParams.firstStep.selectedKt = kt.data.data.map(m => m.id)
          this.submitParams.firstStep.selectedDt = dt.data.data.map(m => m.id)
          this.submitParams.firstStep.selectedMdt = mdt.data.data.map(m => m.id)
          this.submitParams.firstStep.selectedTt = tt.data.data.map(m => m.id)
          // this.submitParams.firstStep.selectedLdt = ldt.data.data.map(m => m.id)

          this.templateLoading = false
        })).catch(e => {
          this.templateLoading = false
        })
    },
    fetchCatlogsAndAssociations() {
      this.associationLoading = true
      axios.all([
        GetWebsiteCatalogs(this.website.id),
        GetAssociations(this.website.id)])
        .then(axios.spread((catalogs, associations) => {
          this.dataSource.secondStep.associations = associations.data
          this.associationLoading = false
          this.dataSource.thirdStep.catalogs = catalogs.data
          this.dataSource.thirdStepRemoate.catalogs = catalogs.data
          this.dataSource.thirdStepRemoate.associations = associations.data
        })).catch(e => {
          this.associationLoading = false
        })
    },
    // 模版预览
    handleTemplatePreview() {
      if (!this.ids.length) {
        this.$alert('产品为空！', 'Error')
        return
      }
      // 必须选择项
      if (!(
        this.submitParams.firstStep.selectedTt.length &&
          this.submitParams.firstStep.selectedKt.length &&
          this.submitParams.firstStep.selectedDt.length &&
          // this.submitParams.firstStep.selectedLdt.length &&
          this.submitParams.firstStep.selectedMdt.length
      )) {
        this.$alert('检查模版的选择！', 'Error')
        return
      }
      const vars = {
        product_ids: this.ids,
        k_id: this.submitParams.firstStep.selectedKt,
        t_id: this.submitParams.firstStep.selectedTt,
        d_id: this.submitParams.firstStep.selectedDt,
        md_id: this.submitParams.firstStep.selectedMdt,
        ld_id: this.submitParams.firstStep.selectedLdt,
        src: this.source
      }
      templatePreview(vars).then(response => {
        this.templatePreviewDialogVisible = true
        this.dataSource.firstStep.templatePreviewData = response.data
      })
    },
    fetchAssociations() {
      GetAssociations(this.website.id).then(response => {
        this.dataSource.secondStep.associations = response.data
      })
    },
    handleFetchWebsiteCatalogs() {
      GetWebsiteCatalogs(this.website.id).then(respone => {
        this.dataSource.thirdStep.catalogs = respone.data
        this.dataSource.thirdStepRemoate.catalogs = respone.data
      })
    },
    handleSecondStepAdd() {
      const tmp = this.$refs.propTree.getCheckedNodes().filter(v => {
        if (!('children' in v)) {
          return v
        }
      })
      const existed = this.submitParams.secondStep.tableData.map(v => {
        return v.id
      })

      tmp.map(v => {
        if (existed.indexOf(v.id) === -1) {
          this.submitParams.secondStep.tableData.push({
            impact_price: _coos_mapper[v.name] || 0,
            impact_weight: 0,
            id: v.id,
            position: v.position,
            name: v.name,
            id_attribute_group: v.id_attribute_group
          })
        }
      })
      this.$refs.propTree.setCheckedKeys([])
    },
    handleSecondStepRemove() {
      const tmp = this.$refs.propTree.getCheckedNodes()
        .filter(v => {
          if (!('children' in v)) {
            return v
          }
        })
        .map(v => {
          return v.id
        })

      this.submitParams.secondStep.tableData = this.submitParams.secondStep.tableData
        .filter(v => {
          return tmp.indexOf(v.id) === -1
        })
      this.$refs.propTree.setCheckedKeys([])
    },
    hide() {
      this.childFormVisible = false
      this.$emit('cancelExportDialog', false)
    },
    handleExport(choice) {
      this.exportLoading = true
      const _vars = {
        w_id: this.website.id, // 目标网址
        ids: this.ids, // 选中产品
        first_step: this.submitParams.firstStep, // 模板
        first_step_single: this.submitParams.firstStep_single, // 如果手动修改单个产品的基本信息,后台不会使用模板来替换
        second_step: this.submitParams.secondStep, // associations
        third_step: _.cloneDeep(this.submitParams.thirdStep), // 目录 总价 是否可用 配置
        excel: choice,
        source: this.source,
        process_type: this.process_type
      }
      const temp = _.cloneDeep(_vars.third_step)
      _vars.third_step.target_catalogs = _vars.third_step.target_catalogs.map(m => m.id)
      if (choice === 'excel') { // 只是检测excel预览一下
        product_export(_vars).then(response => {
          this.$alert(
            `<a href="${response.file}" target="_blank" style="text-decoration: underline; color: #409EFF">${response.filename}</a>`,
            '检测Excel', {
              dangerouslyUseHTMLString: true
            })
          this.exportLoading = false
        }).catch(e => {
          this.exportLoading = false
        })
      } else {
        this.$prompt('请输入描述', '填写描述', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          //  文件太大传到后台会失败，每次最多上传x个产品，分多次提交
          _vars.ids = this.ids
          _vars.description = value + '|产品ID' + _vars.ids.join(',')
          product_export(_vars).then(response => {
            this.$emit('reload')
            this.$notify({
              title: '成功提交，正在后台发送',
              message: '上传结果将在通知中显示!',
              type: 'success'
            })
            this.exportLoading = false
            _vars.third_step = temp
          }).catch(e => {
            this.exportLoading = false
            _vars.third_step = temp
          })
        }).catch(() => {
          _vars.third_step = temp
          this.$message({
            type: 'info',
            message: '取消输入'
          })
          this.exportLoading = false
        })
      }
    },
    handleRemoteEdit(choice) {
      this.exportLoading = true
      const _vars = {
        w_id: this.website.id, // 目标网址
        ids: this.ids, // 选中产品
        first_step: this.submitParams.firstStep, // 模板
        remote: this.submitParams.thirdStepRemoate, // 远程编辑参数
        source: this.source,
        process_type: this.process_type
      }
      this.$prompt('请输入描述', '填写描述', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        _vars.description = value
        product_export(_vars).then(response => {
          this.$emit('reload')
          this.$notify({
            title: '成功',
            message: '已经添加至任务队列,处理结果将在通知中显示!',
            type: 'success'
          })
          this.exportLoading = false
        }).catch(e => {
          this.exportLoading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
        this.exportLoading = false
      })
    },
    showAddCategoryDialog(data) {
      this.submitParams.addCategory = {
        name: '',
        active: '1',
        id_parent: data.id,
        description: '',
        meta_title: '',
        meta_description: '',
        meta_keywords: '',
        friendly_url: ''
      }

      // this.$nextTick(() => {
      //   this.$refs.mt_export_component.destroyTinymce()
      //   this.$refs.mt_export_component.initTinymce()
      //   this.$refs.mt_export_component.setContent('')
      // })
      this.$nextTick(() => {
        if (this.$refs.mt_export_component.hasInit) {
          this.$refs.mt_export_component.setContent('')
        }
      }
      )
      this.addCategoryDialogVisible = true
    },
    handleAddCategory() {
      this.addCategoryLoading = true
      AddCategory(Object.assign(this.submitParams.addCategory,
        { website_id: this.website.id }))
        .then(response => {
          this.addCategoryLoading = false
          this.addCategoryDialogVisible = false
          this.handleFetchWebsiteCatalogs()
        })
        .catch(e => {
          this.addCategoryLoading = false
        })
    },
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.name.toLocaleLowerCase().indexOf(value.toLocaleLowerCase()) !== -1
    }// method end
  }
}
</script>

<style scoped>
  .mt-add-category-dialog >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 48px;
  }

  .export-component >>> .mt-supplier-code-input {
    width: 80%;
  }
</style>
